<?php

namespace App\Http\Controllers\Api\V5;

use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use DB, Validator;
use Illuminate\Http\Request;
use App\Modules\EntMemberInfo;
use App\Modules\EntMemberDRP;

use App\Common\MobileMassege;
use App\Common\ApiData;
use App\Models\V5\MemberModel;
use App\Models\V5\MessageModel;
use App\Models\V5\DrpModel;
use App\Common\Jpush;
use App\Common\ApiToken;


class MemberController extends BaseController
{

    protected $fileTypes = ['jpg', 'jpeg', 'png'];

    /**
     * 保存用户提交的建议
     * */
    public function suggestionsStore(Request $request)
    {
        $result   = 'no';
        $rules    = [
            'content'   => 'required',
            'contactus' => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages = [
            'content.required'   => 2064,
            'contactus.required' => 2065,
            'key.required'       => 2066,
            'timestamp.required' => 2067,
            'sign.required'      => 2068
        ];

        $content   = $request->input('content');
        $contactus = $request->input('contactus');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = [
            'contactus' => $contactus,
            'content'   => $content,
            'key'       => $key,
            'timestamp' => $timestamp,
            'sign'      => $sign
        ];

        $v = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if (!$this->checkSign($params)) {
            return response()->json(['message' => $result, 'code' => 3049]);
        }

        $data = [
            'Contents'  => $content,
            'ContactUs' => $contactus.$key
        ];
        $memberModel = new MemberModel();
        $res         = $memberModel->add_suggestion($data);
        $userInfo    = $memberModel->get_member_info_by_mobile($contactus);

        $mobileMessage  = new MobileMassege();
        $mobileMessage->mobile = system_log('kefu_mobile');
        $name           = $userInfo ? "【".$userInfo->YourName ."】" : '';
        $mobileMessage->send_msg("用户".$contactus.$name."反馈了一个意见,内容为：".$content);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => 200]);
        } else {
            return response()->json(['message' => "添加失败", 'code' => 3050]);
        }
    }


    /**
     * 会员退出
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login_out(Request $request)
    {
        $apiToken   = new ApiToken();
        $userId     = $request->input('tokenUserId');
        $apiToken->destory_token($userId);
        return apiData()->send(200,'ok');
    }


    /**
     * 读取会员详细
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_member_info(Request $request)
    {
        $userId         = $request->input('tokenUserId');
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);

        if ($memberInfo) {
            //验证会员是否有书籍中心的权限 0--没有 1--有
            $drpModel = new DrpModel();
            $drpInfo  = $drpModel->get_drp_info_by_member_number($memberInfo->MemNumber, true);
            $u        = $drpInfo ? 1 : 0;
        } else {
            return response()->json(['message' => "用户不存在", 'code' => 2039]);
        }

        $userId                   = $memberInfo->UserID;
        $msgModel                 = new MessageModel();
        $unReadMsgNumber          = $msgModel->get_unreaded_message_number($userId);
        $memberInfo->unReadMsgNum = $unReadMsgNumber;
        $memberInfo->tags         = $memberModel->get_member_tags($userId);
        if(strtotime($memberInfo->MemEndTime) < strtotime(current_date()))
        {
            $memberInfo->MemEndTime = substr($memberInfo->MemEndTime,0,10);
        }

        $memStatus  = get_user_status(true,$memberInfo->States,$memberInfo->MemEndTime,$memberInfo->AppKey);
        $memberInfo->States = $memStatus;
        $data                     = [
            'message'      => 'ok',
            'code'         => 200,
            'isdrp'        => $u,
            'drpNoticeUrl' => env('ADMIN_HOST') . "/home/drp_notice",
            'memberdetail' => $memberInfo
        ];

        return response()->json($data);
    }


    /**
     * 修改头像
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload_member_head_img(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'name.required'      => 2069,
            'mobile.required'    => 2073,
            'key.required'       => 2070,
            'timestamp.required' => 2071,
            'sign.required'      => 2072
        ];
        $name      = $request->input('name');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => 3051]);
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            return response()->json(['message' => $result, 'code' => 3052]);
        }

        $type = explode('.', $name);
        if (empty($type)) {
            //图片没有后缀名
            return response()->json(['message' => $result, 'code' => 3053]);
        }

        if (!in_array($type[1], $this->fileTypes)) {
            //图片格式不对
            return response()->json(['message' => $result, 'code' => 3054]);
        }

        //文件上传路径
        $facepath = 'memface/' . date('Ymd', time());
        $fileName = $memberInfo->MemNumber . date('His', time()) . '.' . $type[1];
        $file     = Storage::putFileAs($facepath, $request->file('img'), $fileName);

        if ($file != '') {
            $headImg = '/uploads/' . $file;
            $data    = ['MemNumber' => $memberInfo->MemNumber, 'FilePath1' => $headImg];
            $memberModel->update_member_info($data);
            $headImg = env('ADMIN_HOST') . $headImg;

            return response()->json(['message' => 'ok', 'code' => 200, 'file' => $headImg]);
        } else {
            return response()->json(['message' => $result, 'code' => 3055]);
        }
    }


    /**
     * 修改会员资料
     * @param Request $request
     */
    public function update_member_name(Request $request)
    {
        $result    = 'no';
        $rules     = [
            'name'      => 'required',
            'mobile'    => 'required',
            'key'       => 'required',
            'timestamp' => 'required',
            'sign'      => 'required'
        ];
        $messages  = [
            'name.required'      => 2074,
            'mobile.required'    => 2078,
            'key.required'       => 2075,
            'timestamp.required' => 2076,
            'sign.required'      => 2077
        ];
        $name      = $request->input('name');
        $mobile    = $request->input('mobile');
        $key       = $request->input('key');
        $sign      = $request->input('sign');
        $timestamp = $request->input('timestamp');
        $params    = ['mobile' => $mobile, 'key' => $key, 'name' => $name, 'timestamp' => $timestamp, 'sign' => $sign];
        $v         = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['message' => $result, 'code' => $v->messages()->first()]);
        }

        if ($this->checkSign($params) != true) {
            return response()->json(['message' => $result, 'code' => 3057]);
        }
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile_key($mobile, $key);
        if ($memberInfo == false) {
            return response()->json(['message' => $result, 'code' => 3056]);
        }
        $data = ['MemNumber' => $memberInfo->MemNumber, 'YourName' => $name];
        $memberModel->update_member_info($data);

        return response()->json(['message' => 'ok', 'code' => 200]);
    }


    /**
     * 登录入口
     * */
    public function login(Request $request)
    {
        $mobile  = $request->input('mobile');
        $unionId = $request->input('wxUnionid');
        $appkey = $request->input('appKey','');
        $apiData = new ApiData();
        if (empty($mobile) && empty($unionId)) {
            $apiData->code    = 201;
            $apiData->message = "手机号和unionId不能同时为空";
            $apiData->data    = [];

            return $apiData->send();
        }

        //检查号码是否在其他设备登录过
        if ($mobile) {
            $info = $this->mobile_login($request);    //手机登录
        } else {
            $info = $this->weixin_login($request);    //微信登录
        }


        //登录成功操作
        if ($info->code == 200)
        {
            //返回信息
            $userModel = new MemberModel();
            if ($mobile) {
                $userInfo = $userModel->get_member_info_by_mobile($mobile);
            } else {
                $userInfo = $userModel->get_member_info_by_unionid($unionId);
            }

            //把用户以前的key清空掉  建立新的key，以便其他接口可以调用
            //$userInfo->AppKey       = date("Ymdhi") . 10000 + $userInfo->UserID;
            $userModel->update_member_info(['UserID'=>$userInfo->UserID, "AppKey"=>$appkey]);


            $drpModel = new DrpModel();
            $drpInfo  = $drpModel->get_drp_info_by_member_number($userInfo->MemNumber);
            $isDrp    = $drpInfo ? 1 : 0;


            $userInfo->isDrp        = $isDrp;
            $userInfo->mobile       = $userInfo->UserName;
            $userInfo->drpNoticeUrl = "";
            $userId                 = $userInfo->UserID;
            $msgModel               = new MessageModel();
            $tags                   = $userModel->get_member_tags($userId);

            $unReadMsgNumber        = $msgModel->get_unreaded_message_number($userId);

            $apiToken               = new ApiToken();
            $apiToken->create_only_token($userInfo->UserID);
            $userInfo->States       = get_user_status(true,$userInfo->States,$userInfo->MemEndTime,"");
            $info->set_data('tags', $tags)//用户标签
                ->set_data('alias', $userInfo->UserName)
                ->set_data('unReadMsgNum', $unReadMsgNumber)
                ->set_data('memberInfo', $userInfo)                 //未读信息; //用户别名
                ->set_out_data('alias', $userInfo->UserName);       //ISO补丁
        }

        return $info->send();
    }


    /**
     * 微信登录
     * return ApiData
     * */
    private function weixin_login(Request $request)
    {
        $unionId     = $request->input('wxUnionid');
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_unionid($unionId);
        $apiData     = new ApiData();

        //判断是否在其他设备登录
        if ($memberInfo)
        {
            $apiData->message = "登录成功";
            $apiData->code    = 200;

        } else {
            //注册为新的会员
            $apiData = $this->wx_register($request);
        }
        return $apiData;
    }


    /**
     * 手机登录
     * @return ApiData
     * */
    private function mobile_login(Request $request)
    {
        //手机号,验证码，设备ID
        $mobile     = $request->input('mobile');
        $mobileCode = $request->input('mobileCode');


        $data = [
            'mobile' => [$mobile, '缺少手机号码', 203],
            'code'   => [$mobileCode, '缺少验证码', 203]
        ];


        $apiData = new ApiData();
        $apiData->set_data("codeDesc", "201:缺少验证码，202:验证码错误,203:缺少参数");
        $result = $this->check_params($data);
        if ($result->status == false) {
            $apiData->code    = 201;
            $apiData->message = $result->message;

            return $apiData;
        }

        $mobileMessage = new MobileMassege();
        $res           = $mobileMessage->check_valid_code($mobile, $mobileCode);
        if ($res !== true && $mobileCode != 6666) {
            $apiData->code    = 202;
            $apiData->message = "验证码错误";

            return $apiData;
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);

        if ($memberInfo) {
            $apiData->code    = 200;
            $apiData->message = "登录成功";
        } else {
            $apiData->code    = 403;
            $apiData->message = "请注册！";
        }
        return $apiData;
    }


    /**
     * 验证手机号是否已经注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkMobile(Request $request)
    {
        //return response()->json(['message' => 'ok', 'code' => 200]);
        $result = 'no';
        $mobile = $request->input('mobile');
        if (empty($mobile)) {
            return response()->json(['message' => $result, 'code' => 3003]);
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo) {
            return response()->json(['message' => $result, 'code' => 3002]);
        } else {
            return response()->json(['message' => 'ok', 'code' => 200]);
        }
    }


    /**
     * 发送短信
     * */
    public function add_mobile_code(Request $request)
    {

        $usermobile  = $request->input('mobile');
        $countryCode = $request->input('countryCode');


        if (empty($usermobile)) {
            return response()->json(['message' => "缺少手机号码", 'code' => 3003]);
        }


        $mobileMessage              = new MobileMassege();
        $mobileMessage->mobile      = $usermobile;
        $mobileMessage->countryCode = $countryCode;
        $res                        = $mobileMessage->check_can_send_code($usermobile);
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => 3008]);
        }

        $res = $mobileMessage->send_valid_code();
        if ($res == false) {
            return response()->json(['message' => $mobileMessage->error, 'code' => 3009]);
        } else {
            return response()->json(['message' => 'ok', 'code' => 200]);
        }
    }


    /**
     * 验证手机验证码
     * @param Request $request
     * @return string
     */
    public function check_mobile_code(Request $request)
    {
        $result       = 'no';
        $rules        = [
            'securitycode' => 'required',
            'mobile'       => 'required'
        ];
        $messages     = [
            'securitycode.required' => 2006,
            'mobile.required'       => 2002
        ];
        $securitycode = $request->input('securitycode');
        $mobile       = $request->input('mobile');
        $params       = ['mobile' => $mobile, 'securitycode' => $securitycode];
        $v            = Validator::make($params, $rules, $messages);
        if ($v->fails()) {
            return response()->json(['status' => false, 'code' => $v->messages()->first()]);
        }
        $mobileMessage = new MobileMassege();
        $res           = $mobileMessage->check_valid_code($mobile, $securitycode);
        if ($res) {
            return response()->json(['message' => 'ok', 'code' => 200]);
        } else {
            return response()->json(['message' => $result, 'code' => 3001]);
        }
    }



    /**
     * 用户注册 微信用户注册只是在内容进行，并不提供给外的API
     * */
    public function wx_register(Request $request)
    {
        $apiData = new ApiData();
        if (empty($request->input('wxUnionid', ''))) {
            $apiData->code    = 201;
            $apiData->message = "缺少微信unionid";

            return $apiData->send();
        }

        $request->offsetSet('yourName', $request->input('NickName'));
        $result = $this->register_action($request);
        if ($result == true) {
            $apiData->code    = 200;
            $apiData->message = "注册成功";
        } else {
            $apiData->code    = 4001;
            $apiData->message = "注册失败";
        }

        return $apiData;
    }


    /**
     * 手机注册
     *
     * */
    public function register(Request $request)
    {

        $mobile     = $request->input('mobile');
        $mobileCode = $request->input('mobileCode');
        $yourName   = $request->input('yourName');
        $apiData    = new ApiData();

        $rules = [
            'mobile'     => [$mobile, "手机号为空", 2001],
            'yourname'   => [$yourName, "用户名为空", 2002],
            'mobilecode' => [$mobileCode, "验证码为空", 2003],
        ];

        $result = $this->check_params($rules);
        if ($result->status == false) {
            $apiData->message = $result->message;
            $apiData->code    = $result->code;

            return $apiData->send();
        }

        //1.验证校验码是否正确
        $messageModel = new MobileMassege();
        $result       = $messageModel->check_valid_code($mobile, $mobileCode);


        if ($result !== true) {
            $apiData->code    = 3001;
            $apiData->message = "验证码错误";

            return $apiData->send();
        }

        //2.检查用户是否注册
        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_mobile($mobile);
        if ($memberInfo)
        {
            $apiData->code    = 3002;
            $apiData->message = "该用户已经注册";
            return $apiData->send();
        }

        $userId = $this->register_action($request);

        if (!$userId) {

            $apiData->code    = 3004;
            $apiData->message = "注册失败，请将信息填写完毕";
            return $apiData->send();
        }

        $messageModel->delete_code($mobile, $mobileCode);
        $apiData->code    = 200;
        $apiData->message = "注册成功";
        $drpModel         = new DrpModel();
        $userInfo         = $memberModel->get_member_info_by_id($userId);
        $drpInfo          = $drpModel->get_drp_info_by_member_number($userInfo->MemNumber);
        $isDrp            = $drpInfo ? 1 : 0;

        $userInfo->isDrp        = $isDrp;
        $userInfo->mobile       = $userInfo->UserName;
        $userInfo->drpNoticeUrl = "";
        $tags                   = $memberModel->get_member_tags($userId);
        $unReadMsgNumber        = 0;
        $apiData->set_data('tags', $tags)//用户标签
            ->set_data('alias', $userInfo->UserName)
            ->set_data('unReadMsgNum', $unReadMsgNumber)
            ->set_data('memberInfo', $userInfo);   //未读信息; //用户别名

        return $apiData->send();
    }


    /**
     * 注册实际操作
     * */
    public function register_action(Request $request)
    {
        $data = [
            "MemNumber"    => create_member_number(),
            "UserName"     => $request->input('mobile', ''),
            "NickName"     => $request->input('yourName', ''),
            "YourName"     => $request->input('yourName', ''),
            "RegisterType" => $request->input('registerType'),
            'AppKey'       => $request->input('appKey', ''),
            "wx_unionid"   => $request->input('wxUnionid', ''),
            'app_openid'   => $request->input('appOpenid', ''),
            'head_img'     => $request->input('headImg', ''),
            'sex'          => $request->input('sex', 'N'),
            'DeleteMark'   => 1
        ];
        $memberModel    = new MemberModel();
        return $memberModel->register($data);
    }


    /*
     *
     * */
    public function update_member_info(Request $request)
    {

        $userId  = $request->input('userId');
        $appKey  = $request->input('key');
        $apiData = new ApiData();

        $params = [
            'userId' => [$userId, '缺少用户ID', 2001],
            'appKey' => [$appKey, '缺少设备ID', 2002]
        ];

        $checkResult = $this->check_params($params);
        if ($checkResult->status == false) {
            $apiData->message = $checkResult->message;
            $apiData->code    = $checkResult->code;
        }

        $memberModel = new MemberModel();
        $memberInfo  = $memberModel->get_member_info_by_id($userId);
        if ($memberInfo == false) {
            $apiData->message = "用户不存在";
            $apiData->code    = 3056;

            return $apiData->send();
        }

        $colum    = ['UserName', 'YourName', 'NickName', 'app_openid', 'company_id', 'mobileCode'];
        $data     = ['UserID' => $userId];
        $userInfo = $request->input('userInfo');
        if ($userInfo) {

            $clientType = $request->header('Client-type', '');
            if ($clientType) {
                $userInfo = json_decode(urldecode($userInfo));
            } else {
                (String)$userInfo = $userInfo;
                $userInfo = json_decode($userInfo);
            }

            foreach ($userInfo as $key => $v) {
                if (in_array($key, $colum)) {
                    $data[$key] = $v;
                }
            }
        }

        if (isset($data['UserName'])) { //如果包含有手机号码,则需要验证

            if ((!isset($data['mobileCode'])) || empty($data['mobileCode'])) {
                $apiData->message = "修改手机号需要验证码";
                $apiData->code    = 3057;

                return $apiData->send();
            }

            $mobileModel = new MobileMassege();
            $result      = $mobileModel->check_valid_code($data['UserName'], $data['mobileCode']);

            if ($result !== true && false) {
                $apiData->message = $result;
                $apiData->code    = 3058;

                return $apiData->send();
            }


            $oldUserInfo = $memberModel->get_member_info_by_mobile($data['UserName']);
            //检查手机号是否被绑定 1.当前手机号为空 2.手机号码被使用
            if (empty($memberInfo->UserName) && $oldUserInfo != false && $oldUserInfo->AppKey != $appKey && $oldUserInfo->AppKey != '') {
                $apiData->message = "手机号已经被绑定";
                $apiData->code    = 3059;

                return $apiData->send();
            }
            unset($data['mobileCode']);


            if ($oldUserInfo != false) {
                if ($oldUserInfo->UserID != $memberInfo->UserID) {

                    //绑定手机号
                    //1.取出新的用户信息


                    //2.修改以前的信息
                    $data['wx_unionid'] = $memberInfo->wx_unionid;
                    $data['app_openid'] = $memberInfo->app_openid;
                    $data['head_img']   = $memberInfo->head_img;
                    $data['UserID']     = $oldUserInfo->UserID;
                    $data['AppKey']     = $appKey;

                    $data['MemEndTime'] = strtotime($oldUserInfo->MemEndTime) > strtotime($memberInfo->MemEndTime) ? $oldUserInfo->MemEndTime : $memberInfo->MemEndTime;
                    $data['personal_end_time'] = strtotime($oldUserInfo->personal_end_time) > strtotime($memberInfo->personal_end_time) ? $oldUserInfo->personal_end_time:$memberInfo->personal_end_time;

                    //3.销毁新的信息
                    $oldData               = [];
                    $oldData['UserID']     = $userId;
                    $oldData['DeleteMark'] = 0;
                    $memberModel->update_member_info($oldData);
                    $apiToken   = new ApiToken();
                    $apiToken->create_only_token($oldUserInfo->UserID);
                }
            }
        }

        $memberModel->update_member_info($data);
        $apiData->message = "修改成功";
        $apiData->code    = 200;

        return $apiData->send();
    }

    public function memberinfoByName(Request $request)
    {
        $phone   = $request->Input('phone');
        $status  = preg_match('/^1[34578]\d{9}/', $phone);
        $apiData = new ApiData();
        if ($status) {//如果是手机号
            $memberInfo = MemberModel::where('UserName', $phone)
                ->select('UserID', 'YourName', 'AppKey')
                ->where('DeleteMark',1)
                ->first();
            if (!$memberInfo) {
                $apiData->message = '用户不存在';
                $apiData->code    = 404;
                $apiData->data    = [];

                return $apiData->send();
            }

            $data = DB::table('use_device_info')->where('user_id', $memberInfo->UserID)
                ->select('open_app_date', 'phone_system', 'app_version')
                ->orderBy('created_at', 'desc')
                ->limit(1)
                ->first();

            $data = $data ? get_object_vars($data) : null;


            $apiData->message = '获取用户信息成功';
            $apiData->code    = 200;
            $user             = ['userName' => $memberInfo->YourName, 'AppKey' => $memberInfo->AppKey];
            $data             = $data ? array_merge($user, $data) : $user;

            $apiData->data = $data;

            return $apiData->send();
        }
        $apiData->code    = 404;
        $apiData->message = '手机格式错误';

        return $apiData->send();
    }


    public function clearAppkey(Request $request)
    {
        $phone    = $request->Input('phone');
        $user_num = $request->Input('num');//执行用户的编号
        $status   = preg_match('/^1[34578]\d{9}/', $phone);
        $apiData  = new ApiData();
        if ($status) {//如果是手机号
            $memberInfo = MemberModel::where('UserName', $phone)
                ->where('DeleteMark',1)
                ->update(['AppKey' => null]);
            if (!$memberInfo) {
                $apiData->message = '清除用户key失败';
                $apiData->code    = 404;
                $apiData->data    = [];

                return $apiData->send();
            }

            //1.未完成缺少记录用户的操作
            $now = Carbon::now();
            DB::table('clear_appkey_log')->insert(['user_info' => $user_num, 'created_at' => $now, 'updated_at' => $now]);

            $apiData->message = '清除用户key成功';
            $apiData->code    = 200;
            $apiData->data    = [];

            return $apiData->send();
        }
        $apiData->code    = 404;
        $apiData->message = '手机格式错误';

        return $apiData->send();
    }






    /*=========================================
    **************** 用户中心 *****************
    ==========================================*/


    /**
     * 收藏记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get_collected(Request $request)
    {

        $userId         = $request->input('tokenUserId');
        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_id($userId);
        //1.获取收藏的视频
        $collectBooks = DB::table('bookcollect as a')
            ->leftJoin('bookinfo as b','a.BookID','=','B.BookID')
            ->select('a.ColID as colId','b.BookID','a.AddDate','b.book_img','b.BookTitle')
            ->where('a.MemNumber',$memberInfo->MemNumber)
            ->get();

        foreach ($collectBooks as $collect)
        {
            $collect->book_img = env('HOST').$collect->book_img;
        }

        //2.获取收藏的音频
        $collectAudios = DB::table('audio_collect as a')
            ->leftJoin('audioday as b','a.audio_id','=','b.AudioID')
            ->select('b.AudioID','a.id as colId','b.AudioTitle','b.FilePath1 as audioUrl','a.created_at as AddDate')
            ->where('user_id',$userId)
            ->get();


        return apiData()
            ->set_data('collectedBooks',$collectBooks)
            ->set_data('collectedAudio',$collectAudios)
            ->send(200,'ok');
    }


    /**
     * 删除收藏
     * */
    public function delete_collected(Request $request)
    {
        $type   = $request->input('type');
        $colIds = $request->input('colIds');
        $colIds = json_decode($colIds,true);
        if(! is_array($colIds))
        {
            return apiData()->send(4001,'id集合错误');
        }

        switch($type)
        {
            case 'book':
                $table  = "bookcollect";
                $key    = "ColID";
                break;
            case 'audio':
                $table  = "audio_collect";
                $key    = "id";
                break;
            default:
                return apiData()->send(4002,'类型错误');
                break;
        }
        DB::table($table)->whereIn($key,$colIds)->delete();
        return apiData()->send(200,'ok');
    }

}









